package com.mutouren.common.orm;

import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.mutouren.common.exception.ExceptionUtils;
import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;


/**
 * Mybatis配置管理
 * 功能:
 * 1. 加载Mybatis配置文件
 * 2. 创建Sql会话
 */
public class IbatisConfig {
	
	private static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.toString());
	private static Logger runLogger = LogManager.getLogger(LogAlias.SystemRun.toString());
	
	//private static SqlSessionFactory sessionFactory;
	private static Map<String, SqlSessionFactory> mapFactory = new HashMap<String, SqlSessionFactory>();
	//private static Reader reader;

/*	static {
		try {
			reader = Resources.getResourceAsReader("ibatis.cfg.xml");
			//sessionFactory = new SqlSessionFactoryBuilder().build(reader);					
			runLogger.info("system already loaded IbatisConfig");
		} catch (Exception e) {
			// log
			errorLogger.error("loading IbatisConfig error!", e);
			throw ExceptionManager.doUnChecked(e);
		}
	}*/

	private static SqlSessionFactory createSessionFactory(String environment) {
		SqlSessionFactory result = null;
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader("ibatis.cfg.xml");
			result = new SqlSessionFactoryBuilder().build(reader, environment);	
			runLogger.info("IbatisConfig already createSessionFactory: " + environment);
		} catch (Exception e) {
			errorLogger.error("IbatisConfig createSessionFactory fail: " + environment, e);
			throw ExceptionUtils.doUnChecked(e);
		} finally {
			try {
				if(reader != null)
					reader.close();
			} catch(Exception e) {
				errorLogger.error("IbatisConfig reader.close fail!", e);
			}
		}
		
		return result;
	}	
	
//	public static SqlSession getSession() {				
//		try {		
//			return sessionFactory.openSession();
//		} catch (Exception e) {
//			errorLogger.error("Ibatis getSession() error!", e);			
//			throw ExceptionManager.doUnChecked(e);
//		}
//	}
	
	/**
	 * 创建Sql会话
	 * @param cfgName (即：配置文件中environment-id)
	 * @return
	 */
	public synchronized static SqlSession getSession(String cfgName) {
		SqlSessionFactory factory = mapFactory.get(cfgName);
		if(factory == null) {
			factory = createSessionFactory(cfgName);
			mapFactory.put(cfgName, factory);
		}
		
		try {
			return factory.openSession();
		} catch (Exception e) {
			errorLogger.error("Ibatis getSession() error: " + cfgName, e);			
			throw ExceptionUtils.doUnChecked(e);
		}		
	
	}	
}
